package com.gulimall.externalinterface.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.gulimall.common.utils.R;
import com.gulimall.externalinterface.entity.OssFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author ht
 * @Date 2021/8/9 9:05
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/oss")
public class AttachmentController {
    @Autowired
    private OSS ossClient;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;


    @PostMapping("/uploadFiles")
    public R uploadFiles() {
        try {
            String host = "https://" + bucket + "." + endpoint;
            // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
            // 用户上传文件时指定的前缀。
            String dir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            OssFile ossFile = OssFile.builder().accessId(accessId).policy(encodedPolicy).signature(postSignature).dir(dir).host(host).expire(String.valueOf(expireEndTime / 1000)).build();
            return R.ok(200, "上传成功", ossFile);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(400, "上传异常");
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }
}
